 #define _WIN32_WINNT 0x0400

#include <windows.h>
#include <stdio.h>
#include "../Helix.h"
#include "../HObject.h"
#include "FileUtil.h"
#include <string>
#include <vector>
#include <fstream>
#include <iostream>

using namespace std;

namespace helix
{

	TextFileContent::TextFileContent(const char *fileName)
	{
		ifstream fileIn(fileName,ifstream::binary);

		if(!fileIn.is_open())
		{
			success = false;
			Log().Error("Error opening file %s",fileName);
		}
		else{
			fileIn.seekg (0, ios::end);
			int length = fileIn.tellg();
			fileIn.seekg (0, ios::beg);

			// allocate memory:
			char *buffer = new char [length];

			// read data as a block:
			fileIn.read(buffer,length);
			fileIn.close();

			//Make a copy of the buffer and store it as the content.
			fileContent.assign(buffer,length);

			delete[] buffer;

			success=true;
		}
	}

	TextFileContent::~TextFileContent()
	{
		//don't need to do anything
	}

	const char* TextFileContent::getContent()
	{
		return fileContent.c_str();
	}

	bool TextFileContent::successfulRead()
	{
		return success;
	}



	DirectoryList::DirectoryList(const char *directory) : HObject()
	{
		list = new vector<string>();
		this->directory = directory;

		successState = getFileList();
	}
	
	DirectoryList::~DirectoryList()
	{
		delete list;
	}

	int DirectoryList::getFileList()
	{
		HANDLE fileHandle;
		WIN32_FIND_DATA findFileData;
		
		//Find the first file in the directory
		fileHandle = FindFirstFile(directory.c_str(),  &findFileData);

		//Make sure there was not an error.
		if(fileHandle==INVALID_HANDLE_VALUE)
		{
			return FAILURE;
		}
		//If there was not an error put the file name in the list
		list->push_back(findFileData.cFileName);

		while(FindNextFile(fileHandle,&findFileData))
		{
			list->push_back(findFileData.cFileName);
		}

		DWORD error = GetLastError();
		FindClose(fileHandle);
		if (error != ERROR_NO_MORE_FILES) 
		{
			return FAILURE;
		}

		return SUCCESS;
	}

	const char* DirectoryList::getDirectory()
	{
		return directory.c_str();
	}

	int DirectoryList::getSize()
	{
		return (int)list->size();
	}

	const char* DirectoryList::getFile(unsigned int index)
	{
		if(index >=list->size())
			index = (unsigned int)list->size()-1;

		string fileName = (*list)[index];
		return fileName.c_str();
	}
		

	int DirectoryList::successCode()
	{
		return successState;
	}
}

